// Generate Rolling ranking 
// Inputs 
/* each vintage marginable list of stocks
0th_shsz.dta
1st_shsz.dta
2nd_shsz.dta
3rd_shsz.dta
4th_shsz.dta

totrank_rolling.dta         /* stocks rank, inclusion index, based on stock size and volume */ 
*/

use ../src/totrank_rolling, clear

gen date2 = mofd(com_day)
format date2 %tm 
keep if date2>=ym(2010,1)
keep code mkt date2 indic

merge m:1 code using "../src/0th_shsz.dta"
gen v0_marginable = _m
drop _m
replace  v0_marginable = 0 if v0_marginable==1
replace  v0_marginable = 1 if v0_marginable==3

merge m:1 code using "../src/1st_shsz.dta"
gen v1_marginable = _m
drop _m
replace  v1_marginable = 0 if v1_marginable==1
replace  v1_marginable = 1 if v1_marginable==3

merge m:1 code using "../src/2nd_shsz.dta"
gen v2_marginable = _m
drop _m
replace  v2_marginable = 0 if v2_marginable==1
replace  v2_marginable = 1 if v2_marginable==3

merge m:1 code using "../src/3rd_shsz.dta"
gen v3_marginable = _m
drop _m
replace  v3_marginable = 0 if v3_marginable==1
replace  v3_marginable = 1 if v3_marginable==3

merge m:1 code using "../src/4th_shsz.dta"
gen v4_marginable = _m
drop _m
replace  v4_marginable = 0 if v4_marginable==1
replace  v4_marginable = 1 if v4_marginable==3

* V0: 2010/02/13
* V1: 2011/11/25
* V2: 2013/01/25
* V3: 2013/09/06
* V4: 2014/09/12

gen rank_t = .
gsort date2 v0_marginable mkt -indic
by date2 v0_marginable mkt: gen temp=_n
replace rank_t = temp if v0_marginable==0 & (date2>=ym(2010,2) & date2<=ym(2011,10))
replace rank_t = . 	  if v0_marginable==1 & (date2>=ym(2010,2) & date2<=ym(2011,10))
drop temp

gsort date2 v1_marginable mkt -indic
by date2 v1_marginable mkt: gen temp=_n
replace rank_t = temp if v1_marginable==0 & (date2>=ym(2011,11) & date2<=ym(2012,12))
replace rank_t = .    if v1_marginable==1 & (date2>=ym(2011,11) & date2<=ym(2012,12))
drop temp

gsort date2 v2_marginable mkt -indic
by date2 v2_marginable mkt: gen temp=_n
replace rank_t = temp if v2_marginable==0 & (date2>=ym(2013,1) & date2<=ym(2013,8))
replace rank_t = .    if v2_marginable==1 & (date2>=ym(2013,1) & date2<=ym(2013,8))
drop temp

gsort date2 v3_marginable mkt -indic
by date2 v3_marginable mkt: gen temp=_n
replace rank_t = temp if v3_marginable==0 & (date2>=ym(2013,9) & date2<=ym(2014,8))
replace rank_t = .    if v3_marginable==1 & (date2>=ym(2013,9) & date2<=ym(2014,8))
drop temp

gsort date2 v4_marginable mkt -indic
by date2 v4_marginable mkt: gen temp=_n
replace rank_t = temp if v4_marginable==0 & (date2>=ym(2014,9) & date2<=ym(2015,6))
replace rank_t = .    if v4_marginable==1 & (date2>=ym(2014,9) & date2<=ym(2015,6))
drop temp

drop if date2>ym(2015,6)
drop if date2<=ym(2010,1)

gen marginable = 1 if rank_t==.
replace marginable=0 if marginable == .

gsort date2 marginable -rank_t
by date2 marginable: gen q_rank_t = int(5*(_n-1)/_N)+1 
replace q_rank_t = 0  if marginable==1

gen q_rank_t_5=0
replace q_rank_t_5 = 1 if q_rank_t==5

save ../dta/ranking_rolling, replace 
